package com.abc;

import sun.reflect.misc.FieldUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;

@WebServlet("/bbc")
//单次10m,最大100m
@MultipartConfig(maxFileSize =1024*1024*10 ,maxRequestSize =1024*1024*100)
public class bbcaa extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding ("utf-8");
        resp.setContentType ("text/html;charset=utf-8");
        String ma = req.getParameter ("ma");
        System.out.println (ma);
        switch (ma){
            case "data":
                this.readata(req,resp);
                break;
            default:
                resp.sendRedirect ("index.jsp");
                break;
        }
    }

    private void readata(HttpServletRequest req, HttpServletResponse resp) {
        //读取到数据

        Part file = null;
        try {
            file = req.getPart ("file");

        System.out.println (file);
            //获取真实路径
            String realPath = req.getServletContext ().getRealPath ("/WEB-INF/dao");
            System.out.println (file.getName ());
            //获取新的的文件名
            String getdatafilename = datacs.getdatafilename (file.getSubmittedFileName ());
            //使用文件名通过hash算法和运算算出2,3级的文件路径,在拼接文件名,组合出要保存的文件路径
            realPath=datacs.getfatafilepath (realPath,getdatafilename );
            File f = new File (realPath);
            System.out.println (f);
            //判断文件是否存在
            if (!f.exists ()) {
                //不存在就创建
                boolean mkdirs = f.mkdirs ();
                System.out.println (mkdirs);
            }
            //写出文件
            System.out.println (realPath);
           file.write (realPath);
        } catch (IOException e) {
            e.printStackTrace ();
        } catch (ServletException e) {
            e.printStackTrace ();
        }
    }
}
